<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" style="width: 65%">
    <el-tabs
      v-model="activeName"
      type="card"
      class="demo-tabs"
      @tab-click="handleClick"
    >
      <el-tab-pane label="学习时" name="first">
        <div class="demo-collapse">
          <el-collapse v-model="activEapseNames" @change="handleEapseChange">
            <el-collapse-item v-for="item in formData.materialList" :key="item.id" :title="item.name" :name="item.name">
              {{item.name}}
            </el-collapse-item>
          </el-collapse>
        </div>
      </el-tab-pane>
      <el-tab-pane label="阶段测试" name="second">Config</el-tab-pane>
    </el-tabs>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="课程素材" prop="categoryId">
        <el-table :data="formData.materialList">
          <el-table-column type="index"/>
          <el-table-column label="素材名称" align="center" prop="name" />
          <el-table-column label="素材类型" align="center" prop="materialType" />
          <el-table-column label="描述" align="center" prop="description" />
          <el-table-column label="时长（秒）" align="center" prop="videoDuration" />
          <el-table-column prop="orderIndex" label="顺序">
            <template #default="scope">
              <el-input
                v-model="scope.row.orderIndex"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button
                link
                type="danger"
                @click="handleRemove(scope.row.id)"
                v-hasPermi="['course:material:delete']"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-tree-select
          v-model="formData.categoryId"
          :data="categoryTree"
          :props="defaultProps"
          check-strictly
          default-expand-all
          placeholder="请选择分类"
          value-key="categoryId"
        />
      </el-form-item>
      <el-form-item label="课程标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入课程标题" />
      </el-form-item>
      <el-form-item label="课程描述" prop="description">
        <Editor v-model="formData.description" height="150px" />
      </el-form-item>
      <el-form-item label="封面图片路径" prop="coverImage">
        <UploadImg v-model="formData.coverImage" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
    <MaterialList ref="materialListFormRef" @selectMaterialList="getMaterialList" />
  </Dialog>
</template>
<script setup lang="ts">
import { sApi, sVO } from '@/api/course/courses'
import {defaultProps, handleTree} from "@/utils/tree";
import {CategoryApi} from "@/api/course/category";
import MaterialList from './MaterialList.vue'
const materialListFormRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}
import type { TabsPaneContext } from 'element-plus'

const activeName = ref('first')

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}

const activEapseNames = ref([])
const handleEapseChange = (val: string[]) => {
  console.log(val)
}
/** 课程 表单 */
defineOptions({ name: 'sForm' })
const categoryTree = ref() // 树形结构
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  title: undefined,
  description: undefined,
  categoryId: undefined,
  coverImage: undefined,
  materialList:[]
})
const formRules = reactive({
  title: [{ required: true, message: '课程标题不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
function getMaterialList(val){
  const mergedArray = [...formData.value.materialList, ...val];
  let ids = new Set()
  let result = []
  mergedArray.forEach((item) => {
    if (!ids.has(item.id)) {
      ids.add(item.id)
      if(!item.materialId){
        item.materialId = item.id
      }
      item.id = null
      result.push(item)
    }
  })
  formData.value.materialList = result
  console.log(formData.value.materialList)
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  await getTree()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await sApi.gets(id)
      activEapseNames.value = formData.value.materialList.map((item)=>{
        return item.id
      })
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

function openMaterialListForm(){
  materialListFormRef.value.open()
}

function handleRemove(id){
    materialTableData.value = materialTableData.value.filter((item)=>{
      return item.id !== id
  })
}
const getTree = async () => {
  categoryTree.value = []
  const data = await CategoryApi.list()
  let category: Tree = { id: 0, name: '未分类', children: [] }
  category.children = handleTree(data)
  categoryTree.value.push(category)
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as sVO
    if (formType.value === 'create') {
      await sApi.creates(data)
      message.success(t('common.createSuccess'))
    } else {
      await sApi.updates(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    title: undefined,
    description: undefined,
    categoryId: undefined,
    coverImage: undefined,
    materialList:[]
  }
  formRef.value?.resetFields()
}
</script>
<style>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>ht: 600;
}